<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { findById as findEmployee, save as saveEmployee } from '@/api/employer'
import { findByEmployeeId , save as saveCaregiver } from '@/api/caregiver'
import { isArray } from 'element-plus/es/utils/types.mjs'

const router = useRouter()
const route = useRoute()

// 表单引用
const employeeFormRef = ref()
const caregiverFormRef = ref()

// 职位选项
const positionMap = ref([])
let positionMap2 = []

// 资质等级选项
const qualificationLevelOptions = [
  { value: 1, label: '初级' },
  { value: 2, label: '中级' },
  { value: 3, label: '高级' },
  { value: 4, label: '专家' }
]

// 员工表单数据
const employeeForm = reactive({
  name: '',
  gender: 1,
  age: 25,
  idCard: '',
  phone: '',
  email: '',
  address: '',
  positionId: null,
  hireDate: new Date().toISOString().split('T')[0],
  terminationDate: null,
  status: 0,
  emergencyContact: '',
  emergencyPhone: '',
  education: '',
  major: ''
})

// 护工表单数据
const caregiverForm = reactive({
  qualificationLevel: 1,
  specialty: '',
  trainedElderCount: 0,
  experienceYears: 0,
  lastTrainingDate: '',
  evaluationScore: 0
})

// 是否显示护工表单
const showCaregiverForm = computed(() => {
  return employeeForm.positionId === findNursePositionId()
})

// 员工状态选项
const statusOptions = [
  { value: 0, label: '在职' },
  { value: 1, label: '离职' },
  { value: 2, label: '休假' },
  { value: 3, label: '试用期' },
  { value: 4, label: '停职' }
]

// 学历选项
const educationOptions = [
  '初中及以下',
  '高中/中专',
  '大专',
  '本科',
  '硕士',
  '博士'
]

// 表单验证规则
const employeeRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  positionId: [{ required: true, message: '请选择职位', trigger: 'change' }],
  hireDate: [{ required: true, message: '请选择入职日期', trigger: 'change' }],
  emergencyContact: [{ required: true, message: '请输入紧急联系人', trigger: 'blur' }],
  emergencyPhone: [
    { required: true, message: '请输入紧急联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 护工表单验证规则
const caregiverRules = {
  qualificationLevel: [{ required: true, message: '请选择资质等级', trigger: 'change' }],
  experienceYears: [{ required: true, message: '请输入工作经验', trigger: 'blur' }]
}

const findNursePositionId = () => {
  const nursePosition = positionMap2.find(
    position => position.value === '护工'
  )
  return nursePosition ? nursePosition.positionId : 0
}

// 加载员工数据
const loadEmployeeData = async () => {
  try {
    const employeeId = route.query.id
    if (!employeeId) {
      ElMessage.error('无效的员工ID')
      router.go(-1)
      return
    }
    
    // 加载员工信息
    const employeeRes = await findEmployee(employeeId)
    Object.assign(employeeForm, employeeRes.data)
    console.log("employeeForm:",employeeForm)
    // 尝试加载护工信息，如果不存在则忽略
    try {
      if (showCaregiverForm.value) {
        const caregiverRes = await findByEmployeeId (employeeId)
        if (caregiverRes.data) {
          Object.assign(caregiverForm, caregiverRes.data)
        } else {
          // 初始化空的护工表单
          Object.assign(caregiverForm, {
            qualificationLevel: 1,
            specialty: '',
            trainedElderCount: 0,
            experienceYears: 0,
            lastTrainingDate: '',
            evaluationScore: 0
          })
        }
      }
    } catch (error) {
      console.log('未找到护工信息，将创建新的护工记录')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载员工数据失败')
    router.go(-1)
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 验证员工表单
    await employeeFormRef.value.validate()
    
    // 如果是护工，验证护工表单
    if (showCaregiverForm.value) {
      await caregiverFormRef.value.validate()
    }
    
    // 更新员工信息
    await saveEmployee(employeeForm)
    
    // 如果是护工，更新护工信息
    if (showCaregiverForm.value) {
      await saveCaregiver({
        ...caregiverForm,
        employeeId: employeeForm.id
      })
    }
    
    ElMessage.success('更新成功')
    router.go(-1)
  } catch (error) {
    console.error('更新失败:', error)
    if (!error.response) {
      ElMessage.error('请检查表单填写是否正确')
    }
  }
}

// 返回
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  const storedData = localStorage.getItem('positionMap')
  console.log("原始字符串:", storedData)

  if (storedData) {
    if(Array.isArray(JSON.parse(storedData).value)) {
      console.log("解析后类型:", typeof JSON.parse(storedData)) 
      console.log("具体内容:", JSON.parse(storedData).value)
      positionMap2 = JSON.parse(storedData).value
    }
    console.log("具体内容:", JSON.parse(storedData))
    positionMap.value = JSON.parse(storedData)
    console.log("加载的positionMap:", positionMap.value)
  }
  
  loadEmployeeData()
})
</script>

<template>
  <div class="employee-edit-container">
    <el-card class="edit-card">
      <template #header>
        <div class="card-header">
          <span class="title">编辑员工信息</span>
          <div>
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </div>
        </div>
      </template>

      <!-- 员工基本信息表单 -->
      <el-form 
        ref="employeeFormRef"
        :model="employeeForm" 
        :rules="employeeRules"
        label-width="120px"
      >
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="employeeForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="employeeForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number 
                v-model="employeeForm.age" 
                :min="18" 
                :max="70" 
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="employeeForm.idCard" placeholder="请输入18位身份证号" maxlength="18" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">联系信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="employeeForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="employeeForm.email" placeholder="请输入邮箱" type="email" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="address">
          <el-input 
            v-model="employeeForm.address" 
            type="textarea" 
            :rows="2" 
            placeholder="请输入详细地址"
          />
        </el-form-item>

        <el-divider content-position="left">工作信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="positionId">
              <el-select 
                v-model="employeeForm.positionId" 
                placeholder="请选择职位"
                clearable
              >
                <el-option
                  v-for="position in positionMap.value"
                  :key="position.positionId"
                  :label="position.value"
                  :value="position.positionId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker
                v-model="employeeForm.hireDate"
                type="date"
                placeholder="选择入职日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工状态" prop="status">
              <el-select v-model="employeeForm.status" placeholder="请选择状态">
                <el-option
                  v-for="status in statusOptions"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="employeeForm.status === 1">
            <el-form-item label="离职日期" prop="terminationDate">
              <el-date-picker
                v-model="employeeForm.terminationDate"
                type="date"
                placeholder="选择离职日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">紧急联系人</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input v-model="employeeForm.emergencyContact" placeholder="请输入紧急联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急电话" prop="emergencyPhone">
              <el-input v-model="employeeForm.emergencyPhone" placeholder="请输入紧急联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">教育背景</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历" prop="education">
              <el-select 
                v-model="employeeForm.education" 
                placeholder="请选择学历"
                clearable
              >
                <el-option
                  v-for="edu in educationOptions"
                  :key="edu"
                  :label="edu"
                  :value="edu"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-input v-model="employeeForm.major" placeholder="请输入专业" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 护工专属信息表单 -->
      <el-form 
        v-if="showCaregiverForm"
        ref="caregiverFormRef"
        :model="caregiverForm" 
        :rules="caregiverRules"
        label-width="120px"
      >
        <el-divider content-position="left">护工专属信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资质等级" prop="qualificationLevel">
              <el-select 
                v-model="caregiverForm.qualificationLevel" 
                placeholder="请选择资质等级"
              >
                <el-option
                  v-for="level in qualificationLevelOptions"
                  :key="level.value"
                  :label="level.label"
                  :value="level.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专长领域">
              <el-input v-model="caregiverForm.specialty" placeholder="请输入专长领域" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作经验(年)" prop="experienceYears">
              <el-input-number 
                v-model="caregiverForm.experienceYears" 
                :min="0" 
                :max="50" 
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最近培训日期">
              <el-date-picker
                v-model="caregiverForm.lastTrainingDate"
                type="date"
                placeholder="选择培训日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="护理老人数量">
              <el-input-number 
                v-model="caregiverForm.trainedElderCount" 
                :min="0" 
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="综合评分">
              <el-rate 
                v-model="caregiverForm.evaluationScore" 
                :max="5" 
                allow-half
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.employee-edit-container {
  padding: 20px;
}

.edit-card {
  margin: 0 auto;
  max-width: 1000px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.el-divider {
  margin: 30px 0 20px;
}

.el-form-item {
  margin-bottom: 22px;
}
</style>